package cn.z2huo.knowledge.concurrency.semaphore;

import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *
 * @author z2huo
 */
class SemaphoreDemo {

    /**
     * 总共请求数量
     */
    private static final int REQ_COUNT = 10;

    /**
     * 可同时并发执行的线程数量
     */
    private static final int PERMIT_COUNT = 2;

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(REQ_COUNT);

        Semaphore semaphore = new Semaphore(PERMIT_COUNT);

        AtomicInteger index = new AtomicInteger(0);

        Runnable runnable = () -> {
            try {
                try {
                    // 阻塞获取一个许可证
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + " acquire permit " + index.incrementAndGet());
                    // 业务操作。。。
                    ThreadUtil.sleep(1000);
                    // 业务结束，释放一个许可
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        };

        Thread[] threads = new Thread[REQ_COUNT];
        for (int i = 0; i < REQ_COUNT; i++) {
            threads[i] = new Thread(runnable, "Thread-" + i);
        }
        for (int i = 0; i < REQ_COUNT; i++) {
            Thread thread = threads[i];
            thread.start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
